package com.lc.admin.web;

import com.aliyun.oss.OSS;
import com.lc.admin.base.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 项目中所有的文件上传都走这个接口
 */
//@Api("文件上传控制器")
@RestController
@RequestMapping("/upload")
public class UploadWeb {


    @Value("${zhyl.oss.endPoint}")
    String endPoint;

    @Value("${zhyl.oss.bucketName}")
    String bucketName;
    @Autowired
    OSS ossClient;


//    @ApiOperation(value = "单图片上传")
    @PostMapping("/single")
    public ResponseResult singleUpload(MultipartFile file) {
        // 改名  upload1.png
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));   // .png
        String newName = System.currentTimeMillis() + suffix;

        try {
            ossClient.putObject(bucketName, newName, file.getInputStream());

            String filePath = "https://" + bucketName +"."+endPoint+"/"+newName;
            Map<String,String> map = new HashMap<>();
            map.put("msg",filePath);
            return ResponseResult.success(map);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("上传失败");
        }
    }
}
